package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dtos.ReadBehaviorDto;
import com.heima.behavior.pojos.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.model.article.model.UpdateArticleMess;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppThreadLocal;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) throws Exception {
        //1.校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.获取登录用户id
        ApUser apUser = AppThreadLocal.getApUser();
        //表示未登录
        if(apUser==null){
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份不能进行以下操作
        if(apUser.getId()==0){
            return ResponseResult.okResult(405,"游客身份禁止，需进行登录");
        }
//3.查询mongo中是否有数据，如果有，则更新次数，否则新增
        ApReadBehavior readBehavior = mongoTemplate.findOne(
                Query.query(Criteria.where("userId").is(apUser.getId())
                        .and("articleId").is(dto.getArticleId()))
                , ApReadBehavior.class);
        if(readBehavior==null){
            //3.新增mongo
            readBehavior=new ApReadBehavior();
            BeanUtils.copyProperties(dto,readBehavior);
            readBehavior.setCreatedTime(new Date());
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setUserId(apUser.getId().longValue());
            readBehavior.setId(ObjectId.get().toHexString());
            readBehavior.setCount(1);
        }else {
            //更新次数和时间
            readBehavior.setCount(readBehavior.getCount()+dto.getCount());
            readBehavior.setUpdatedTime(new Date());
        }

        mongoTemplate.save(readBehavior);
        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        updateArticleMess.setArticleId(readBehavior.getArticleId());
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        updateArticleMess.setAdd(1);
        //将行为发送至kafka
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(updateArticleMess));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
